package cn.player.act.frag;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import net.tsz.afinal.FinalHttp;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.player.App;
import cn.player.R;
import cn.player.adapter.RightRecomInfoAdapter;
import cn.player.entity.RecomInfo;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.entity.VodDetail;
import cn.player.media.entity.VodListInfo;
import cn.player.media.fragment.BaseFragment;
import cn.player.media.fragment.MediaPlayFragment;
import cn.player.media.util.DateUtil;
import cn.player.media.util.ParseUtil;

public class RecomInfoFragment extends BaseFragment {

    private App app;
    private FinalHttp finalHttp;
    private Context mContext;
    private String recomUrl;
    private List<RecomInfo> mRecomInfos;
    public RightRecomInfoAdapter mRecomInfoAdapter;
    private ListView lvRecom;
    protected MediaPlayFragment mMediaFrag;
    protected String vsId;

    //点播相关信息
    private VodDetail vodDetail;//视频详情
    private List<VodListInfo> vodSelects;//所有选集列表集合
    private List<VodListInfo> vodEpiSelects;//集数列表集合
    private List<VodListInfo> vodBestSelects;//精选列表集合
    private VideoInfo videoInfo;


    public static RecomInfoFragment newInstance(String recomUrl) {
        RecomInfoFragment rFrag = new RecomInfoFragment();
        Bundle args = new Bundle();
        args.putString("recomUrl", recomUrl);
        rFrag.setArguments(args);
        return rFrag;
    }

    @Override
    protected int setContentLayout() {
        // TODO Auto-generated method stub
        return R.layout.right_recom_frag;
    }

    @Override
    protected void findViews(View rootView) {
        // TODO Auto-generated method stub
        super.findViews(rootView);
        lvRecom = (ListView) rootView.findViewById(R.id.lv_recom);
    }

    @Override
    protected void setListensers() {
        // TODO Auto-generated method stub
        super.setListensers();

        lvRecom.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                vsId = app.getBaseUrls().get(Const.KEY_VLIST_URL).getUrl() + "&vsid=" + mRecomInfos.get(position).getVsid();
                initJsonData(vsId);
            }
        });

        lvRecom.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                    case OnScrollListener.SCROLL_STATE_IDLE:
                        mMediaFrag.getMediaController().show();
                        break;
                    case OnScrollListener.SCROLL_STATE_FLING:
                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub

            }
        });
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        app = (App) mContext.getApplicationContext();
        finalHttp = app.getFinalHttp();
        recomUrl = getArguments().getString("recomUrl");
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Log.i("zl", "RecomInfoFragment onActivityCreated");

        if (mMediaFrag == null) {
            mMediaFrag = (MediaPlayFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.ll_play_area);
        }

        if (mRecomInfos != null && mRecomInfos.size() > 0) {
            mRecomInfoAdapter = new RightRecomInfoAdapter(mContext, mRecomInfos, R.layout.right_recom_item_view);
            lvRecom.setAdapter(mRecomInfoAdapter);
        } else {
            initJsonData(recomUrl);
        }

    }

    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        try {
            if (url.equals(recomUrl)) {
                mRecomInfos = ParseUtil.parseDataToCollection(response, "list", RecomInfo.class);
                mRecomInfoAdapter = new RightRecomInfoAdapter(mContext, mRecomInfos, R.layout.right_recom_item_view);
                lvRecom.setAdapter(mRecomInfoAdapter);
            } else if (url.equals(vsId)) {
                vodDetail = ParseUtil.parseDataToEntity(response.optJSONObject("videoset"), "0", VodDetail.class);
                vodSelects = ParseUtil.parseDataToCollection(response, "video", VodListInfo.class);
                setRightSelections();


                videoInfo = new VideoInfo();
                videoInfo.setFlag(Const.VOD);

                if (vodEpiSelects != null && vodEpiSelects.size() > 0) {
                    videoInfo.setTitle(vodEpiSelects.get(0).getT());
                    videoInfo.setVid(vodEpiSelects.get(0).getVid());
                } else if (vodBestSelects != null && vodBestSelects.size() > 0) {
                    videoInfo.setTitle(vodBestSelects.get(0).getT());
                    videoInfo.setVid(vodBestSelects.get(0).getVid());
                } else if (vodSelects != null && vodSelects.size() > 0) {
                    videoInfo.setTitle(vodSelects.get(0).getT());
                    videoInfo.setVid(vodSelects.get(0).getVid());
                }

//				reAddPlayer(videoInfo);

                mMediaFrag.playVideo(videoInfo);


            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.i("zl", "RecomInfoFragment onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);
        Log.i("zl", "RecomInfoFragment onViewCreated");
    }

    /**
     * 重新添加播放器
     */
    private void reAddPlayer(VideoInfo videoInfo) {
        FragmentManager fragMgr = getActivity().getSupportFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
        fragTran.detach(mMediaFrag);
        mMediaFrag.setVideoInfo(videoInfo);
        fragTran.attach(mMediaFrag);
        fragTran.commit();
    }


    /**
     * 设置右侧精选列表和选集列表(选集列表按播放时间排序)
     */
    private void setRightSelections() {
        if (vodSelects == null || vodSelects.size() == 0) {
            return;
        }
        if (vodEpiSelects == null) {
            vodEpiSelects = new ArrayList<VodListInfo>();
        } else {
            vodEpiSelects.clear();
        }
        if (vodBestSelects == null) {
            vodBestSelects = new ArrayList<VodListInfo>();
        } else {
            vodBestSelects.clear();
        }
        for (VodListInfo select : vodSelects) {
            if ("CM01".equals(select.getEm())) {
                vodEpiSelects.add(select);
            } else if ("CM02".equals(select.getEm())) {
                vodBestSelects.add(select);
            }
        }

        sortVodSelect(vodEpiSelects);
        sortVodSelect(vodBestSelects);

    }

    /**
     * 将右侧点播列表按播放时间降序排列
     *
     * @param selects
     */
    private void sortVodSelect(List<VodListInfo> selects) {
        if (selects != null && selects.size() > 0) {
            Collections.sort(selects, new Comparator<VodListInfo>() {

                @Override
                public int compare(VodListInfo lhs, VodListInfo rhs) {

                    // TODO Auto-generated method stub
                    long lhsTime = DateUtil.getMilliseconds(lhs.getPtime(), Const.DATE_TYPE_Y_M_DHMS);
                    long rhsTime = DateUtil.getMilliseconds(rhs.getPtime(), Const.DATE_TYPE_Y_M_DHMS);
                    if (lhsTime < rhsTime) {
                        return -1;
                    } else if (lhsTime > rhsTime) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Log.i("zl", "RecomInfoFragment onStart");
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.i("zl", "RecomInfoFragment onResume");
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.i("zl", "RecomInfoFragment onPause");
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.i("zl", "RecomInfoFragment onStop");
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        Log.i("zl", "RecomInfoFragment onDestroyView");
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("zl", "RecomInfoFragment onDestroy");

    }

    @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();
        Log.i("zl", "RecomInfoFragment onDetach");
    }

}
